package com.jcj.jcjregistry.cluster;

import com.jcj.jcjregistry.http.HttpInvoker;
import com.jcj.jcjregistry.service.JcjRegistryService;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

@Slf4j
public class ServerHealth {
    Cluster cluster;
    long timeout = 5_000;
    final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);

    public ServerHealth(Cluster cluster) {
        this.cluster = cluster;
    }

    public void checkServerHealth() {
        executorService.scheduleAtFixedRate(() -> {
            try {
                updateServers(); // 1.更新服务器状态
                doElect();   // 2.选主
                syncSnapshotFromLeader(); // 3.同步快照
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }, 0, timeout, java.util.concurrent.TimeUnit.MILLISECONDS);
    }

    private void doElect() {
        new Election().electLeader(cluster.getServers());
    }

    private void syncSnapshotFromLeader() {
        Server self = cluster.self();
        Server leader = cluster.leader();
        log.debug(" ===>>> leader version: " + leader.getVersion()
                + ", my version: " + self.getVersion());

        if (!self.isLeader() && self.getVersion() < leader.getVersion()) {
            log.debug(" ===>>> sync snapshot from leader: " + leader);
            Snapshot snapshot = HttpInvoker.httpGet(leader.getUrl() + "/snapshot", Snapshot.class);
            log.debug(" ===>>> sync and restore snapshot: " + snapshot);
            JcjRegistryService.restore(snapshot);

        }
    }

    private void updateServers() {
        List<Server> servers = cluster.getServers();
        servers.stream().parallel().forEach(server -> {
            try {
                if (server.equals(cluster.self())) { // 如果是自己，则不去更新状态
                    return;
                }
                Server server1 = HttpInvoker.httpGet(server.getUrl() + "/info", Server.class);
                log.info(" 健康检测成功 " + server1);
                if (server1 != null) {
                    server.setStatus(true);
                    server.setVersion(server1.getVersion());
                    server.setLeader(server1.isLeader());
                }
            } catch (Exception e) {
                log.error(" 健康检测失败 " + server);
                server.setStatus(false);
                server.setLeader(false);
            }
        });
    }


}
